package com.linkage.jz.bankruptcy.activity.Person;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.activity.RegistLogin.AccountLoginActivity;
import com.linkage.jz.bankruptcy.activity.Vote.ProVoteCreateResultActivity;
import com.linkage.jz.bankruptcy.activity.Vote.ProVoteResultFileActivity;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.LoginInfo;
import com.linkage.jz.bankruptcy.bean.Vote.ProVoteResult;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.activity.register.RegisterActivity;
import com.linkage.seapeak.activity.user.ImageShowActivity;
import com.linkage.seapeak.base.BaseWhiteActivity;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import jp.wasabeef.glide.transformations.CropCircleTransformation;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.linkage.seapeak.activity.user.ImageShowActivity.IMAGE_REQUEST;


/**
 * A login screen that offers login via email/password.
 */
public class PersonSettingActivity extends BaseWhiteActivity implements OnClickListener {
    private static final String TAG = PersonSettingActivity.class.getSimpleName();
    private PublicNoticeDialog noticeDialog;
    private ShapeLoadingDialog shapeLoadingDialog;

    LoginInfo info;

    TextView item_text2, item_text3, item_text4, item_text5;
    TextView btn_logout;
    ImageView item_avatar;

    RelativeLayout re_org, re_phone, re_avatar, re_email, re_nickname;

    public static void start(Context context) {
        Intent intent = new Intent(context, PersonSettingActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_setting, "个人信息");
        shapeLoadingDialog = new ShapeLoadingDialog(this);
        initview();
    }


    //初始化视图
    private void initview() {
        //登录层、下拉层、其它登录方式层
        item_avatar = findViewById(R.id.item_avatar);
        item_text2 = findViewById(R.id.item_other2);
        item_text3 = findViewById(R.id.item_other3);
        item_text4 = findViewById(R.id.item_other4);
        item_text5 = findViewById(R.id.item_other5);


        btn_logout = findViewById(R.id.btn_logout);
        re_org = findViewById(R.id.re_org);
        re_avatar = findViewById(R.id.re_avatar);
        re_email = findViewById(R.id.re_email);
        re_nickname = findViewById(R.id.re_nickname);
        re_phone = findViewById(R.id.re_phone);

        re_org.setOnClickListener(this);
        re_avatar.setOnClickListener(this);
        re_email.setOnClickListener(this);
        re_nickname.setOnClickListener(this);
        re_phone.setOnClickListener(this);
        btn_logout.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        info = BankruptcyApp.loginInfo;
        if (info != null) {
            item_text2.setText(TextUtils.isEmpty(info.getUsername()) ? "" : info.getUsername());
            item_text3.setText(TextUtils.isEmpty(info.getEmail()) ? "未填写" : info.getEmail());
            item_text4.setText(TextUtils.isEmpty(info.getMobile()) ? "未绑定" : info.getMobile());
            item_text5.setText(TextUtils.isEmpty(info.getCompany()) ? "未填写" : info.getCompany());

            Glide.with(this).load(info.getAvatar())
                    .bitmapTransform(new CropCircleTransformation(PersonSettingActivity.this))
                    .placeholder(R.drawable.logo)
                    .into(item_avatar);
        }else{
            fdialog = 2;
            String phonestatus  = SPUtils.getInstance(Consts.SPNAME).getString("setPhone");
            if(!"1".equalsIgnoreCase(phonestatus)) {
                noticeDialog = new PublicNoticeDialog(PersonSettingActivity.this, onClickListener,
                        1, "提示", "请重新登录",
                        "取消", "登录");
            }else {


                noticeDialog = new PublicNoticeDialog(PersonSettingActivity.this, onClickListener,
                        1, "提示", "您的登录手机号已更改，请重新登录",
                        "取消", "登录");
            }
            noticeDialog.show();
        }
    }

    private int fdialog = 1;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.re_org:
                //返回
                PersonSettingOrgActivity.start(this,info.getCompany());
                break;
            case R.id.re_avatar:
                ImageShowActivity.start(PersonSettingActivity.this,
                        info.getAvatar(), ImageShowActivity.FROM_PERSON
                );
//                showPopupWindow();
//                ll_popup.startAnimation(AnimationUtils.loadAnimation(
//                        PersonSettingActivity.this, R.anim.activity_translate_in));
//                pop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.re_email:
//                finish();
                PersonSettingEmailActivity.start(this,info.getEmail());
                break;
            case R.id.re_nickname:
                PersonSettingNickNameActivity.start(this,info.getUsername());
                break;
            case R.id.re_phone:
                PersonSettingPhoneActivity.start(this,info.getMobile());
                break;
//                GetPwdOneActivity.start(this);
            case R.id.btn_logout:

                fdialog = 1;
                noticeDialog = new PublicNoticeDialog(PersonSettingActivity.this,onClickListener,
                        1,"提示","确认退出登录吗？",
                        "取消","确认");
                noticeDialog.show();

                break;
            default:
                break;
        }
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.ll_close:
                    if(fdialog == 1)
                    {

                    }else{
                        MainActivity.start(PersonSettingActivity.this);
                    }
                    noticeDialog.dismiss();
                    break;

                case R.id.btn_chancel_notice:
//                   Boolean flag =  noticelxDialog.cb_agree.isChecked();
                    if(fdialog == 1)
                    {

                    }else{
                        MainActivity.start(PersonSettingActivity.this);
                    }
                    noticeDialog.dismiss();

                    break;

                case R.id.btn_save_notice:

                    if(fdialog == 1)
                    {
                        logout();

                        SPUtils.getInstance(Consts.SPNAME).put("userToken", "");
//                BankruptcyApp.loginInfo = null;
                        BankruptcyApp.userToken = "";
                        BankruptcyApp.loginInfo = null;
                        finish();

                    }else{
                        SPUtils.getInstance(Consts.SPNAME).put("setPhone", "0");
                        RegisterActivity.start(PersonSettingActivity.this);
                    }

                    noticeDialog.dismiss();
                    break;

            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IMAGE_REQUEST && resultCode == Activity.RESULT_OK
                && null != data) {
            try {
                String imagePath = data.getStringExtra("imagePath");
                Luban.with(this)
                        .load(imagePath)
                        .ignoreBy(1000)
                        .filter(new CompressionPredicate() {
                            @Override
                            public boolean apply(String path) {
                                return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                            }
                        })
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                                shapeLoadingDialog.setLoadingText("上传中...");
                                shapeLoadingDialog.setCanceledOnTouchOutside(false);
                                shapeLoadingDialog.show();
                            }

                            @Override
                            public void onSuccess(File file) {
                                String filename = file.getAbsolutePath();
                                updatePic(filename);
                            }

                            @Override
                            public void onError(Throwable e) {
                                shapeLoadingDialog.dismiss();
                            }
                        }).launch();

            } catch (Exception e) {
            }
        }
    }


    public void updatePic(String file) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)//设置连接超时时间
                .readTimeout(30, TimeUnit.SECONDS)//设置读取超时时间
                .build();
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
//            Toast.makeText(AccountLoginActivity.this, "没有token", Toast.LENGTH_SHORT).show();
//            getTokenMain(mobile,code,pwd);
            return;
        }

        File mfile = new File(file);
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("userToken", userToken)
                .addFormDataPart("appid", Consts.appid)
                .addFormDataPart("nonce", rom)
                .addFormDataPart("timestamp", timestamp)
                .addFormDataPart("token", BankruptcyApp.tokeninfo.getToken())
                .addFormDataPart("Filedata", mfile.getName(),
                        RequestBody.create(MediaType.parse("image/jpg"), mfile));

        RequestBody requestBody = builder.build();
        String url = Consts.WEBURL_UPLOADIMAGE;

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.e(TAG, "onFailure: " + e);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        Toast.makeText(MainActivity.this, "失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                shapeLoadingDialog.dismiss();
                Log.e(TAG, "成功" + response);
                String str = response.body().string();
                try {
                    JSONObject object = new JSONObject(str);

                    if (object.optInt("code") == 0) {
                        JSONObject data = object.optJSONObject("data");
                        final String strUlr = data.optString("url");
                        final String realUrl = data.optString("realSourceUrl");
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                SaveData(strUlr, realUrl);
//                                Toast.makeText(PersonSettingActivity.this, "保存成功", Toast.LENGTH_SHORT).show();

                            }

                        });
//                        finish();

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                showToast("保存失败");

                            }

                        });

                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                    ;
                }
            }
        });

    }


    public void SaveData(final String avatar, final String showurl) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken(null);
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId", "");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.appid)
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("avatar", avatar)
                .add("token", BankruptcyApp.tokeninfo.getToken())
//                .add("token", "")
                .add("userId", userId)
                .add("userToken", userToken)
                .add("type", "1")
                .build();

        String url = Consts.WEBURL_MODIFYPERSON;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        //更新UI
                        showToast("保存失败");

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try {
                    JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                showToast("保存成功");
                                if (BankruptcyApp.loginInfo != null)
                                    BankruptcyApp.loginInfo.setAvatar(showurl);
                                Glide.with(PersonSettingActivity.this).load(showurl)
                                        .bitmapTransform(new CropCircleTransformation(PersonSettingActivity.this))
                                        .placeholder(R.drawable.logo)
                                        .into(item_avatar);
                            }

                        });
//                        finish();

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                showToast("保存失败");

                            }

                        });

                    }
                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            showToast("保存失败");
                        }

                    });
                }
            }
        });
    }

    private void logout() {
//        shapeLoadingDialog.setLoadingText("加载中...");
//        shapeLoadingDialog.setCanceledOnTouchOutside(false);
//        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId", "");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.appid)
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
                .build();

        String url = Consts.WEBURL_LOGOUT;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        //更新UI
//                        showToast("保存失败");

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
//                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try {
                    JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI

                            }

                        });
//                        finish();

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
//                                showToast("保存失败");

                            }

                        });

                    }
                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
//                            showToast("保存失败");
                        }

                    });
                }
            }
        });
    }


}

